package com.smxy.mall.controller;

import com.smxy.mall.annotation.JwtIgnore;
import com.smxy.mall.common.Response;
import com.smxy.mall.entity.News;
import com.smxy.mall.model.CommonPageRequest;
import com.smxy.mall.model.news.NewsCatRequest;
import com.smxy.mall.model.news.NewsRequest;
import com.smxy.mall.service.NewsService;
import com.smxy.mall.utils.Common;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.domain.*;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;

@Api(tags = "文章模块")
@RestController
@RequestMapping("/news")
public class NewsController {
    @Resource
    private NewsService newsService;

    @JwtIgnore
    @ApiOperation("新增/编辑文章")
    @PostMapping("/news_edit")
    public Object newsEdit(@Valid NewsRequest newsRequest) {
        return Response.success(newsService.save(newsRequest));
    }

    @JwtIgnore
    @ApiOperation("文章列表")
    @GetMapping("/news_list")
    public Object newsList(@Valid CommonPageRequest commonPageRequest, @RequestParam("categoryId")Integer categoryId) {
        Sort sort = Sort.by(Sort.Direction.DESC,"id");
        Pageable pageable = PageRequest.of((commonPageRequest.getPage()-1),commonPageRequest.getSize(),sort);
        if(Common.isId(categoryId+"")){
            return Response.success(newsService.newsList(categoryId,pageable));
        }else{
            return Response.success(newsService.newsList(pageable));
        }
    }

    @JwtIgnore
    @ApiOperation("文章详情")
    @GetMapping("/news_detail")
    public Object newsDetail(@RequestParam("id")Integer id){
        return Response.success(newsService.detail(id));
    }

    @JwtIgnore
    @ApiOperation("新增/编辑分类")
    @PostMapping("/news_cat_edit")
    public Object newsCatEdit(@Valid NewsCatRequest newsCatRequest){
        return Response.success(newsService.save(newsCatRequest));
    }

    @JwtIgnore
    @ApiOperation("分类列表")
    @GetMapping("/news_cat_list")
    public Object newsCatList(@RequestParam("pid")Integer pid){
        return Response.success(newsService.catList(pid));
    }
}
